package com.mvc.rpc;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

/**
 * 覆盖代理注册
 * @author JayEinstein
 */
public class CoverProxyBeanFactoryPostProcess implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        // 代理接口
        String[] rpcProxyNames = beanFactory.getBeanNamesForType(RpcProxyFactoryBean.class);
        if (rpcProxyNames.length < 1) {
            return;
        }

        for (String rpcProxyName : rpcProxyNames) {

            // 获得代理接口类型
            rpcProxyName = BeanFactoryUtils.transformedBeanName(rpcProxyName);
            Class<?> type = beanFactory.getType(rpcProxyName);

            // 接口下的所有beanName
            String[] beanNamesForType = beanFactory.getBeanNamesForType(type);

            // 只有一个就算了
            if (beanNamesForType.length < 1) {
                continue;
            }

            for (String beanName : beanNamesForType) {

                // 非目标bd
                if (beanName.equals(rpcProxyName)) {
                    continue;
                }

                if (beanFactory instanceof DefaultListableBeanFactory) {
                    DefaultListableBeanFactory dbf = (DefaultListableBeanFactory) beanFactory;
                    dbf.removeBeanDefinition(beanName);
                }

            }



        }

    }

}
